﻿using KPIS.DBM;
using KPIS.GERP.ESS.BLL;
using KPIS.GERP.ESS.MODEL;
using KPIS.GERP.GFMS.APP.App_UI.Commons;
using KPIS.GERP.GFMS.BLL;
using KPIS.GERP.GFMS.DAL;
using KPIS.GERP.GFMS.IBLL;
using KPIS.GERP.GFMS.IDAL;
using KPIS.GERP.GFMS.MODEL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace KPIS.GERP.GFMS.APP.App_UI.Forms
{
    public partial class FIM_PaymentIncomes : System.Web.UI.Page
    {
        Main main = new Main();
        IBLL_FIM_Payments pay = new B_FIM_Payments();
        IBLL_FIM_PaymentCheques paycheque = new B_FIM_PaymentCheques();
        IBLL_FIM_MoneyRequests mr = new B_FIM_MoneyRequests();
        IBLL_FIM_MoneyRequestDtls mrd = new B_FIM_MoneyRequestDtls();
        IBLL_BGM_MAS_Source source = new B_BGM_MAS_Source();
        IBLL_HRM_MP_WorkAreas area = new B_HRM_MP_WorkAreas();
        B_MessageSend send = new B_MessageSend();
        IBLL_FIM_MAS_Events ev = new B_FIM_MAS_Events();
        IBLL_BGM_ProjectOperation oper = new B_BGM_ProjectOperation();
        IBLL_BGM_ProjectOperationReport operRpt = new B_BGM_ProjectOperationReport();
        IBLL_FIM_SystemControls sc = new B_FIM_SystemControls();
        IBLL_HRM_PR_PayrollDtls prd = new B_HRM_PR_PayrollDtls();
        IBLL_FIM_MAS_ExpenseRates rate = new B_FIM_MAS_ExpenseRates();
        IBLL_FIM_MAS_Methods met = new B_FIM_MAS_Methods();
        IBLL_FIM_MAS_BankAccounts acc = new B_FIM_MAS_BankAccounts();
        IBLL_FIM_Cheques cheque = new B_FIM_Cheques();
        IBLL_HRM_PS_Employees emplist = new B_HRM_PS_Employees();
        IBLL_HRM_PS_EMP_BOOK_BANKS emp_acc = new B_HRM_PS_EMP_BOOK_BANKS();
        IBLL_ICM_MasContactBank con_acc = new B_ICM_MasContactBank();
        IBLL_FIM_Payroll prl = new B_FIM_Payroll();
        IBLL_ACM_GENERATE_ACCOUNT_Auto acm = new B_ACM_GENERATE_ACCOUNT_Auto();
        IDAL_ACM_GENERATE_ACCOUNT_Auto acm2 = new D_ACM_GENERATE_ACCOUNT_Auto();
        IBLL_CodeGenerate cg = new B_CodeGenerate();
        IBLL_FIM_Transfers transfer = new B_FIM_Transfers();
        IBLL_FIM_MAS_Contacts con = new B_FIM_MAS_Contacts();
        IBLL_FIM_Receives r = new B_FIM_Receives();
        //DBManager dbManager = new DBManager(SystemInfo._DataProvider, SystemInfo._ConnectionString);

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //======= test only =========
                //Session["EmpSeq"] = "1";
                int year = main.GetSystemControls().default_bgm_year.Value;
                txtBgmYear.Text = year.ToString();
                txtReceiveBgmYear.Text = year.ToString();
                txtBgmYear.MinValue = year - 10;
                txtBgmYear.MaxValue = year + 1;
                lblBgmYear.Text = year.ToString();

                //===========================

                //LoadDDLFilterEventSeq();
                LoadDDLFilterBgmSourceSeq();
                LoadDDLFilterWorkAreaSeq();
                LoadRblMethodSeq();
                lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
                LoadDDLBankAccSeq();
                ddlBankAccSeq_SelectedIndexChanged(null, null);
                LoadDDLChequeSeq();
                LoadDDLFromBankAccSeq();
                LoadDDLToContactBankAccSeq(null);
                ViewState["_tmpConId"] = null;
                ViewState["_tmpEmpSeq"] = null;
                rblMethodSeq_SelectedIndexChanged(null, null);
                LoadDDLContactSeq();

                LoadRadGrid2();
            }
        }

        protected void LoadRadGrid2()
        {
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strWorkAreaSeq = ddlFilterWorkAreaSeq.SelectedValue;
            string strEventSeq = "27";//ddlFilterEventSeq.SelectedValue;
            string strEmpSeq = Session["EmpSeq"].ToString();
            var dataSource = pay.GetFull(strBgmSourceSeq, strBgmYear, strWorkAreaSeq, strEventSeq, "0");

            RadGrid2.DataSource = dataSource;
            //bool loadOnlyApproved = cmdMultiSelectStop.Visible && pnlMultiApprove1.Visible;

            //if (!loadOnlyApproved)
            //{
            //    RadGrid2.DataSource = dataSource;
            //}
            //else
            //{
            //    RadGrid2.DataSource = dataSource.Where(o => o.record_status_name == "อนุมัติแล้ว");
            //}
        }
        protected void LoadData(string strPaySeq)
        {
            if (string.IsNullOrEmpty(strPaySeq))
            {
                lblPaySeq.Text = "";
                txtPayName.Text = "";
                lblPayRefNo.Text = "";
                dpPayDate.SetValue(DateTime.Today);
                rblMethodSeq.SelectedValue = "2";
                rblMethodSeq_SelectedIndexChanged(null, null);
                //PanelCheque.Visible = true;
                //PanelTransfer.Visible = false;
            }
            else
            {
                M_FIM_Payments payInfo = pay.GetInfo(strPaySeq);
                lblPaySeq.Text = strPaySeq;
                ddlContactSeq.SelectedValue = payInfo.contact_seq.ToString();
                lblAmount.Text = (payInfo.amount ?? 0).ToString("#,##0.00");
                lblPayRefNo.Text = payInfo.ref_no;
                dpPayDate.SetValue(payInfo.pay_date.Value);
                txtPayName.Text = payInfo.pay_name;
                rblMethodSeq.SelectedValue = payInfo.method_seq.ToString();

                if (rblMethodSeq.SelectedValue.Equals("3"))
                {
                    ddlFromBankAcc.SelectedValue = payInfo.from_bank_acc_id.ToString();
                    LoadDDLToContactBankAccSeq(main.ConvertNullInt(ddlContactSeq.SelectedValue));
                    ddlToConBankAcc.SelectedValue = payInfo.to_bank_acc_id.ToString();
                }
                else if (rblMethodSeq.SelectedValue.Equals("4"))
                {
                    LoadDDLToContactBankAccSeq(main.ConvertNullInt(ddlContactSeq.SelectedValue));
                    ddlToConBankAcc.SelectedValue = payInfo.to_bank_acc_id.ToString();
                }
            }

            LoadRadGrid3();

            if (PanelCheque.Visible)
            {
                LoadDataCheque();
                cmdAddNew.Visible = cmdAddNew.Visible = (cmdInsert1.Visible || cmdUpdate1.Visible);
                PanelEditCheque.Visible = false;
                cmdInsert2.Visible = true;
                cmdUpdate2.Visible = false;
                cmdDelete2.Visible = false;
                cmdCancel2.Visible = false;
                PanelTransfer.Visible = false;
            }
        }

        protected void LoadDataCheque()
        {
            if (lblPaySeq.Text.Length == 0)
            {
                ViewState["Cheque"] = paycheque.GetFull("-1", null);
            }
            else
            {
                ViewState["Cheque"] = paycheque.GetFull(lblPaySeq.Text, null);
            }

            grdCheque.DataSource = (IList<M_FIM_PaymentCheques>)ViewState["Cheque"];
            grdCheque.DataBind();
        }

        protected void LoadDDLContactSeq()
        {
            ddlContactSeq.DataSource = con.GetList(null);
            ddlContactSeq.DataBind();

            main.InsertEmptyDDLAll(ddlContactSeq);
            ddlContactSeq.SelectedIndex = 0;
        }

        //protected void LoadDDLFilterEventSeq()
        //{
        //    ddlFilterEventSeq.DataSource = ev.GetList();
        //    ddlFilterEventSeq.DataBind();

        //    main.InsertEmptyDDLAll(ddlFilterEventSeq);
        //    ddlFilterEventSeq.SelectedIndex = 0;
        //}

        protected void LoadDDLFilterBgmSourceSeq()
        {
            ddlFilterBgmSourceSeq.DataSource = source.GetFull(true);
            ddlFilterBgmSourceSeq.DataBind();

            ddlFilterBgmSourceSeq.SelectedIndex = 0;
        }

        protected void LoadDDLFilterWorkAreaSeq()
        {
            ddlFilterWorkAreaSeq.DataSource = area.GetFull();
            ddlFilterWorkAreaSeq.DataBind();
            main.InsertEmptyDDLAll(ddlFilterWorkAreaSeq);

            ddlFilterWorkAreaSeq.SelectedIndex = 0;
        }

        protected void LoadRblMethodSeq()
        {
            rblMethodSeq.DataSource = met.GetList();
            rblMethodSeq.DataBind();
        }

        protected void LoadDDLBankAccSeq()
        {
            ddlBankAccSeq.DataSource = acc.GetList("2", ddlFilterBgmSourceSeq.SelectedValue, null, null);
            ddlBankAccSeq.DataBind();

            ddlBankAccSeq.SelectedIndex = 0;
            LoadDDLChequeSeq();
        }

        protected void LoadDDLFromBankAccSeq()
        {
            ddlFromBankAcc.DataSource = acc.GetList("2", ddlFilterBgmSourceSeq.SelectedValue, null, null);
            ddlFromBankAcc.DataBind();
            //main.InsertEmptyDDLSelect(ddlFromBankAcc);
            ddlFromBankAcc.SelectedIndex = 0;
        }

        protected void LoadDDLToContactBankAccSeq(int? ConId)
        {
            ddlToConBankAcc.DataSource = con_acc.GetList(ConId);
            ddlToConBankAcc.DataBind();
            //main.InsertEmptyDDLSelect(ddlToConBankAcc);
            ddlToConBankAcc.SelectedIndex = 0;
        }

        protected void LoadDDLChequeSeq()
        {
            if (lblPaySeq.Text.Length == 0)
            {
                ddlChequeSeq.DataSource = cheque.GetList(ddlBankAccSeq.SelectedValue, null, null, "1");
            }
            else
            {
                ddlChequeSeq.DataSource = cheque.GetList(ddlBankAccSeq.SelectedValue, lblPaySeq.Text, null, "1");
            }
            ddlChequeSeq.DataBind();

            main.InsertEmptyDDLSelect(ddlChequeSeq);
            ddlChequeSeq.SelectedIndex = 0;
        }

        protected bool CheckData1()
        {
            bool bOK = true;
            string strError = "";

            if (dpPayDate.GetStringValue().Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("วันที่ทำรายการ");
            }
            else if (txtPayName.Text.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("ชื่อรายการจ่ายเงิน");
            }
            else if (ddlContactSeq.SelectedValue.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("จ่ายเงินให้กับ");
            }
            else if (lblAmount.Text.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("รวมจำนวนเงิน");
            }
            else if ((main.ConvertNullDouble(lblAmount.Text) ?? 0) <= 0)
            {
                bOK = false;
                strError = "[รวมจำนวนเงิน] ห้ามน้อยกว่า หรือเท่ากับ 0";
            }

            if (rblMethodSeq.SelectedIndex.Equals(2))
            {
                if (String.IsNullOrEmpty(ddlFromBankAcc.SelectedValue))
                {
                    bOK = false;
                    strError = main.ErrorEmpty("บัญชีโอน");
                }
            }

            if (rblMethodSeq.SelectedIndex.Equals(2) || rblMethodSeq.SelectedIndex.Equals(3))
            {
                if (String.IsNullOrEmpty(ddlToConBankAcc.SelectedValue))
                {
                    bOK = false;
                    strError = main.ErrorEmpty("บัญชีรับ");
                }
            }


            if (!bOK)
                main.MessageAlert(Page, strError);

            return bOK;
        }

        protected bool CheckData2()
        {
            bool bOK = true;
            string strError = "";

            if (ddlBankAccSeq.SelectedValue.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("บัญชีเงินฝาก");
            }
            else if (ddlChequeSeq.SelectedValue.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("เช็คเลขที่");
            }
            else if (txtChequeAmount.Text.Length == 0)
            {
                bOK = false;
                strError = main.ErrorEmpty("จำนวนเงิน");
            }

            if (!bOK)
                main.MessageAlert(Page, strError);

            return bOK;
        }

        //============================ control events ==============================
        
        protected void RadGrid2_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "RowClick")
            {
                GridDataItem item = (GridDataItem)e.Item;
                string strRecordStatus = pay.GetInfo(main.WebString(item["pay_seq"].Text)).record_status;
                lblRecordStatus.Text = strRecordStatus;
                //bool bApproved = strRecordStatus == "A";

                PanelEdit1.Visible = true;
                PanelView.Visible = false;
                cmdInsert1.Visible = false;
                cmdUpdate1.Visible = strRecordStatus == "W" || strRecordStatus == "U" || strRecordStatus == "R";
                cmdDelete1.Visible = strRecordStatus == "W" || strRecordStatus == "U" || strRecordStatus == "R";
                //cmdCancel2.Visible = true;
                cmdAddNew.Visible = strRecordStatus == "W" || strRecordStatus == "U" || strRecordStatus == "R";
                divReceive.Visible = strRecordStatus == "W" || strRecordStatus == "U" || strRecordStatus == "R";
                cmdApprove.Visible = true;
                cmdApprove.Enabled = strRecordStatus == "W" || strRecordStatus == "U" || strRecordStatus == "R";
                cmdRealPay.Visible = strRecordStatus == "A" && main.WebString(item["real_pay_date"].Text).Length == 0
                    && (main.WebString(item["method_seq"].Text) == "1" || main.WebString(item["method_seq"].Text) == "3");
                PanelMessageSend.Visible = false;
                divControl1.Visible = true;
                LoadData(main.WebString(item["pay_seq"].Text));
                rblMethodSeq_SelectedIndexChanged(null, null);

                if (strRecordStatus == "A")
                    rblMethodSeq.Enabled = false;
                else
                    rblMethodSeq.Enabled = true;

                //ddlFromBankAcc.SelectedValue = item["from_bank_acc_id"].Text;
                //if (item["contact_seq"].Text.Length > 0)
                //    ddlToConBankAcc.SelectedValue = item["to_bank_acc_id"].Text;
                //else ddlToBankAcc.SelectedValue = item["to_bank_acc_id"].Text;

                rblMethodSeq.Enabled = false;
                LoadDdlReceiveSeq();
            }
        }

        protected void RadGrid2_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            if (!e.IsFromDetailTable)
            {
                LoadRadGrid2();
            }
        }

        protected void grdCheque_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "cmdEdit")
            {
                GridDataItem item = (GridDataItem)e.Item;

                PanelEditCheque.Visible = true;
                cmdAddNew.Visible = false;
                cmdInsert2.Visible = false;
                cmdUpdate2.Visible = cmdUpdate1.Visible;
                cmdDelete2.Visible = cmdUpdate1.Visible;
                cmdCancel2.Visible = true;

                lblPayChequeSeq.Text = main.WebString(item["pay_cheque_seq"].Text);
                ddlBankAccSeq.SelectedValue = main.WebString(item["bank_acc_seq"].Text);
                LoadDDLChequeSeq();
                ddlChequeSeq.SelectedValue = main.WebString(item["cheque_seq"].Text);
                txtChequeAmount.Text = main.WebString(item["amount"].Text);
                lblIndex.Text = item.ItemIndex.ToString();
            }
            else if (e.CommandName == "cmdPayCheque")
            {
                PanelPayCheque.Visible = true;

                GridDataItem item = (GridDataItem)e.Item;
                M_FIM_Cheques model = cheque.GetInfo(main.WebString(item["cheque_seq"].Text));

                lblChequeSeq.Text = model.cheque_seq.ToString();
                lblChequeBookSeq.Text = model.cheque_book_seq.ToString();
                lblChequeNo.Text = model.cheque_no.ToString();
                lblBankAccSeq.Text = model.bank_acc_seq.ToString();
                dpChequePayDate.SetValue(model.pay_date);
                dpChequeDate.SetValue(model.cheque_date);
                txtReceiver.Text = model.receiver;
                rblChequeStatus.SelectedValue = model.cheque_status;
                rblChequeStatus_SelectedIndexChanged(null, null);
                txtActualPayDate.SetValue(model.pay_date);
                // txtChequeRemarks.Text = model.cheque_remarks;
            }
        }

        protected void grdCheque_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                GridDataItem dataItem = (GridDataItem)e.Item;
                string ChequeStatus = main.WebString(dataItem["cheque_status"].Text);

                ((LinkButton)e.Item.FindControl("cmdEdit")).Visible = lblRecordStatus.Text == "W" || lblRecordStatus.Text == "R";
                ((Button)e.Item.FindControl("cmdPayCheque")).Visible = (ChequeStatus == "1" || ChequeStatus == "2"); // && lblRecordStatus.Text == "A";
            }
        }

        protected void cmdAddNew_Click(object sender, EventArgs e)
        {
            PanelEditCheque.Visible = true;

            cmdAddNew.Visible = false;
            cmdDelete2.Visible = false;
            cmdInsert2.Visible = (cmdUpdate1.Visible || cmdInsert1.Visible);
            cmdUpdate2.Visible = false;
            divControl1.Visible = false;

            ddlChequeSeq.SelectedIndex = 0;
            txtChequeAmount.Text = lblAmount.Text;
        }

        protected void cmdDelete1_Click(object sender, EventArgs e)
        {
            string strPaySeq = lblPaySeq.Text;

            M_FIM_Payments info = new M_FIM_Payments();
            info.pay_seq = Convert.ToInt32(strPaySeq);
            info.updated_by = main.ConvertNullInt(Session["EmpSeq"].ToString());
            info.updated_when = DateTime.Now;

            pay.Delete(info);

            PanelEdit1.Visible = false;
            PanelView.Visible = true;
            LoadRadGrid2();
            RadGrid2.DataBind();
            // RadGrid2AfterBind();
        }

        protected void cmdInsert1_Click(object sender, EventArgs e)
        {
            if (!CheckData1())
            {
                return;
            }

            M_FIM_Payments info = new M_FIM_Payments();

            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strWorkAreaSeq = ddlFilterWorkAreaSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strEventSeq = "27";
            string strPayName = txtPayName.Text;
            string strRefNo = cg.GetNextCode(TransectionType.FimPaymentsRefNo, strBgmSourceSeq == "1" ? "1" : "2");
            DateTime strPayDate = dpPayDate.GetDateValue().Value;
            string strMoneyReqSeq = null;// lblMoneyReqSeq.Text;
            string strEmpSeq = null;// (lblEmpSeq.Text.Length > 0 ? lblEmpSeq.Text : null);
            string strContactSeq = ddlContactSeq.SelectedValue;
            string strContactPersonSeq = null;
            string strPetitionSeq = null;// (lblPetitionSeq.Text.Length > 0 ? lblPetitionSeq.Text : null);
            string strPetitionDtlsSeq = null;// (lblPetitionDtlsSeq.Text.Length > 0 ? lblPetitionDtlsSeq.Text : null);
            string strAmount = lblAmount.Text; //(PanelPayrollDeduction.Visible ? lblPayAmountExcludeDeduction.Text : lblPayAmount.Text);
            //string strVatPercent = txtVatPercent.Text;
            //string strTaxPercent = txtTaxPercent.Text;
            string strVatAmount = lblVatAmount.Text;
            string strTaxAmount = "0";// lblAmountTax.Text;
            string strMethodSeq = rblMethodSeq.SelectedValue;
            string strUserID = Session["EmpSeq"].ToString();

            string strFromBankAcc = ddlFromBankAcc.SelectedValue;
            string strToConBankAcc = ddlToConBankAcc.SelectedValue;

            DateTime dtNow = DateTime.Now;

            info.bgm_source_seq = Convert.ToInt32(strBgmSourceSeq);
            info.work_area_seq = Convert.ToInt32(string.IsNullOrEmpty(strWorkAreaSeq) ? "0" : strWorkAreaSeq);
            info.bgm_year = Convert.ToInt32(strBgmYear);
            info.event_seq = main.ConvertNullInt(strEventSeq);
            info.pay_name = strPayName;
            info.ref_no = strRefNo;
            info.pay_date = main.ConvertNullDateTime(strPayDate);
            info.money_req_seq = main.ConvertNullInt(strMoneyReqSeq);
            info.emp_seq = main.ConvertNullInt(strEmpSeq);
            info.contact_seq = main.ConvertNullInt(strContactSeq);
            info.contact_person_seq = main.ConvertNullInt(strContactPersonSeq);
            info.petition_seq = main.ConvertNullInt(strPetitionSeq);
            info.petition_dtls_seq = main.ConvertNullInt(strPetitionDtlsSeq);
            info.amount = main.ConvertNullDouble(strAmount);
            info.vat = main.ConvertNullDouble(strVatAmount);
            info.tax = main.ConvertNullDouble(strTaxAmount);
            info.method_seq = main.ConvertNullInt(strMethodSeq);

            info.created_by = main.ConvertNullInt(strUserID);
            info.created_when = main.ConvertNullDateTime(dtNow);

            if (PanelTransfer.Visible)
            {
                info.to_bank_acc_id = main.ConvertNullInt(strToConBankAcc);

                if (rblMethodSeq.SelectedValue.Equals("3"))
                    info.from_bank_acc_id = main.ConvertNullInt(strFromBankAcc);
                else if (rblMethodSeq.SelectedValue.Equals("4"))
                    info.from_bank_acc_id = null;
            }

            string strPaySeq = pay.Insert(info);

            foreach(GridDataItem item in RadGrid3.Items)
            {
                var receiveModel = r.GetInfo(main.WebString(item["receive_seq"].Text));
                receiveModel.pay_seq = Convert.ToInt32(strPaySeq);
                receiveModel.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                receiveModel.updated_when = DateTime.Now;
                r.UpdatePaySeq(receiveModel);
            }

            if (PanelCheque.Visible)
            {
                foreach (GridDataItem item in grdCheque.Items)
                {
                    M_FIM_PaymentCheques chequeInfo = new M_FIM_PaymentCheques();
                    chequeInfo.pay_seq = main.ConvertNullInt(strPaySeq);
                    chequeInfo.cheque_seq = main.ConvertNullInt(main.WebString(item["cheque_seq"].Text));
                    chequeInfo.amount = main.ConvertNullDouble(main.WebString(item["amount"].Text));
                    chequeInfo.record_status = "W";
                    chequeInfo.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                    chequeInfo.created_when = DateTime.Now;

                    paycheque.Insert(chequeInfo);

                    M_FIM_Cheques chq = cheque.GetInfo(main.WebString(item["cheque_seq"].Text));
                    chq.cheque_date = main.ConvertNullDateTime(main.WebString(item["cheque_date"].Text));
                    chq.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                    chq.updated_when = DateTime.Now;
                    cheque.Update(chq);
                }
            }

            main.MessageAlert(Page, "รหัสรายการคือ [" + strRefNo + "]");
            LoadData(strPaySeq);

            PanelEdit1.Visible = true;
            PanelView.Visible = false;
            cmdInsert1.Visible = false;
            cmdUpdate1.Visible = true;
            cmdDelete1.Visible = true;
            //cmdCancel2.Visible = true;
            cmdAddNew.Visible = true;
            cmdApprove.Visible = true;
            cmdApprove.Enabled = true;
            cmdRealPay.Visible = false;
            PanelMessageSend.Visible = false;
            divControl1.Visible = true;
        }

        protected void cmdUpdate1_Click(object sender, EventArgs e)
        {
            if (!CheckData1())
            {
                return;
            }

            M_FIM_Payments info = new M_FIM_Payments();

            string strPaySeq = lblPaySeq.Text;
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strWorkAreaSeq = ddlFilterWorkAreaSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strEventSeq = "27";
            string strPayName = txtPayName.Text;
            string strRefNo = lblPayRefNo.Text;
            //if (String.IsNullOrEmpty(lblPayRefNo.Text)) strRefNo = cg.GetNextCode(TransectionType.FimPaymentsRefNo, strBgmSourceSeq);
            //else strRefNo = lblPayRefNo.Text;
            DateTime strPayDate = dpPayDate.GetDateValue().Value;
            string strMoneyReqSeq = null;// lblMoneyReqSeq.Text;
            string strEmpSeq = null;//(lblEmpSeq.Text.Length > 0 ? lblEmpSeq.Text : null);
            string strContactSeq = ddlContactSeq.SelectedValue;
            string strContactPersonSeq = null;//(lblContactPersonSeq.Text.Length > 0 ? lblContactPersonSeq.Text : null);
            string strPetitionSeq = null;//(lblPetitionSeq.Text.Length > 0 ? lblPetitionSeq.Text : null);
            string strPetitionDtlsSeq = null;//(lblPetitionDtlsSeq.Text.Length > 0 ? lblPetitionDtlsSeq.Text : null);
            string strAmount = lblAmount.Text; //(PanelPayrollDeduction.Visible ? lblPayAmountExcludeDeduction.Text : lblPayAmount.Text);
            //string strVatPercent = txtVatPercent.Text;
            //string strTaxPercent = txtTaxPercent.Text;
            string strVatAmount = lblVatAmount.Text;
            string strTaxAmount = "0";//lblAmountTax.Text;
            string strMethodSeq = rblMethodSeq.SelectedValue;
            string strFromBankAcc = ddlFromBankAcc.SelectedValue;
            string strToConBankAcc = ddlToConBankAcc.SelectedValue;

            string strUserID = Session["EmpSeq"].ToString();

            DateTime dtNow = DateTime.Now;

            info.pay_seq = Convert.ToInt32(strPaySeq);
            info.bgm_source_seq = Convert.ToInt32(strBgmSourceSeq);
            info.work_area_seq = Convert.ToInt32(string.IsNullOrEmpty(strWorkAreaSeq) ? "0" : strWorkAreaSeq);
            info.bgm_year = Convert.ToInt32(strBgmYear);
            info.event_seq = main.ConvertNullInt(strEventSeq);
            info.pay_name = strPayName;
            info.ref_no = strRefNo;
            info.pay_date = main.ConvertNullDateTime(strPayDate);
            info.money_req_seq = main.ConvertNullInt(strMoneyReqSeq);
            info.emp_seq = main.ConvertNullInt(strEmpSeq);
            info.contact_seq = main.ConvertNullInt(strContactSeq);
            info.contact_person_seq = main.ConvertNullInt(strContactPersonSeq);
            info.petition_seq = main.ConvertNullInt(strPetitionSeq);
            info.petition_dtls_seq = main.ConvertNullInt(strPetitionDtlsSeq);
            info.amount = main.ConvertNullDouble(strAmount);
            //info.vat_rate = main.ConvertNullDouble(strVatPercent);
            //info.tax_rate = main.ConvertNullDouble(strTaxPercent);
            info.vat = main.ConvertNullDouble(strVatAmount);
            info.tax = main.ConvertNullDouble(strTaxAmount);
            info.method_seq = main.ConvertNullInt(strMethodSeq);

            info.created_by = main.ConvertNullInt(strUserID);
            info.created_when = main.ConvertNullDateTime(dtNow);

            if (PanelTransfer.Visible)
            {
                info.to_bank_acc_id = main.ConvertNullInt(strToConBankAcc);
                
                if (rblMethodSeq.SelectedValue.Equals("3"))
                    info.from_bank_acc_id = main.ConvertNullInt(strFromBankAcc);
                else if (rblMethodSeq.SelectedValue.Equals("4"))
                    info.from_bank_acc_id = null;
            }

            pay.Update(info);

            var recModels = r.GetPayments(Convert.ToInt32(strPaySeq));
            foreach (var recModel in recModels)
            {
                recModel.pay_seq = null;
                r.UpdatePaySeq(recModel);
            }
            foreach (GridDataItem item in RadGrid3.Items)
            {
                var receiveModel = r.GetInfo(main.WebString(item["receive_seq"].Text));
                receiveModel.pay_seq = Convert.ToInt32(strPaySeq);
                receiveModel.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                receiveModel.updated_when = DateTime.Now;
                r.UpdatePaySeq(receiveModel);
            }

            if (PanelCheque.Visible)
            {
                foreach (GridDataItem item in grdCheque.Items)
                {
                    M_FIM_PaymentCheques chequeInfo = new M_FIM_PaymentCheques();
                    chequeInfo.pay_seq = main.ConvertNullInt(strPaySeq);
                    chequeInfo.cheque_seq = main.ConvertNullInt(main.WebString(item["cheque_seq"].Text));
                    chequeInfo.amount = main.ConvertNullDouble(main.WebString(item["amount"].Text));
                    chequeInfo.record_status = "W";

                    if (main.WebString(item["pay_cheque_seq"].Text).Length == 0)
                    {
                        chequeInfo.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                        chequeInfo.created_when = DateTime.Now;
                        paycheque.Insert(chequeInfo);
                    }
                    else
                    {
                        chequeInfo.pay_cheque_seq = Convert.ToInt32(main.WebString(item["pay_cheque_seq"].Text));
                        chequeInfo.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                        chequeInfo.updated_when = DateTime.Now;
                        paycheque.Update(chequeInfo);
                    }

                    M_FIM_Cheques chq = cheque.GetInfo(main.WebString(item["cheque_seq"].Text));
                    chq.cheque_date = main.ConvertNullDateTime(main.WebString(item["cheque_date"].Text));
                    chq.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                    chq.updated_when = DateTime.Now;
                    cheque.Update(chq);
                }
            }

            PanelView.Visible = true;
            PanelEdit1.Visible = false;
            LoadRadGrid2();
            RadGrid2.DataBind();
        }

        protected void cmdCancel1_Click(object sender, EventArgs e)
        {
            PanelEdit1.Visible = false;
            PanelView.Visible = true;
        }

        protected void cmdInsert2_Click(object sender, EventArgs e)
        {
            if (!CheckData2())
            {
                return;
            }

            Double? lstAmt = 0;
            Double? payAmt = 0;
            if (!String.IsNullOrEmpty(lblAmount.Text)) payAmt = Convert.ToDouble(lblAmount.Text);

            M_FIM_PaymentCheques info = new M_FIM_PaymentCheques();
            info.cheque_seq = main.ConvertNullInt(ddlChequeSeq.SelectedValue);
            info.cheque_name = ddlChequeSeq.Text;
            info.amount = main.ConvertNullDouble(txtChequeAmount.Text);
            info.cheque_date = dpChequeDate2.GetDateValue();
            info.record_status = "W";

            List<M_FIM_PaymentCheques> listInfo = (List<M_FIM_PaymentCheques>)ViewState["Cheque"];
            listInfo.Add(info);
            if (listInfo.Count > 0)
            {
                for (int i = 0; i < listInfo.Count; i++)
                {
                    lstAmt += listInfo[i].amount;
                }
                if (lstAmt > payAmt)
                {
                    main.MessageAlert(Page, "พบข้อผิดพลาด! จำนวนเงินในเช็คมากกว่าจำนวนเงินจ่าย");
                    return;
                }
            }
            ViewState["Cheque"] = listInfo;
            grdCheque.DataSource = listInfo;
            grdCheque.DataBind();

            PanelEditCheque.Visible = false;
            cmdAddNew.Visible = true;
            divControl1.Visible = true;
            lblPayChequeSeq.Text = "";
            ddlChequeSeq.SelectedIndex = 0;
        }

        protected void cmdUpdate2_Click(object sender, EventArgs e)
        {
            if (!CheckData2())
            {
                return;
            }

            List<M_FIM_PaymentCheques> listInfo = (List<M_FIM_PaymentCheques>)ViewState["Cheque"];

            M_FIM_PaymentCheques info = listInfo[Convert.ToInt32(lblIndex.Text)];
            info.cheque_seq = main.ConvertNullInt(ddlChequeSeq.SelectedValue);
            info.cheque_name = ddlChequeSeq.Text;
            info.amount = main.ConvertNullDouble(txtChequeAmount.Text);
            info.cheque_date = dpChequeDate2.GetDateValue();
            info.record_status = "W";

            ViewState["Cheque"] = listInfo;
            grdCheque.DataSource = listInfo;
            grdCheque.DataBind();

            PanelEditCheque.Visible = false;
            cmdAddNew.Visible = true;
            divControl1.Visible = true;
        }

        protected void cmdCancel2_Click(object sender, EventArgs e)
        {
            PanelEditCheque.Visible = false;
            cmdAddNew.Visible = true;
            divControl1.Visible = true;
        }

        protected void cmdDelete2_Click(object sender, EventArgs e)
        {
            if (lblPayChequeSeq.Text.Length > 0)
            {
                M_FIM_PaymentCheques info = new M_FIM_PaymentCheques();
                info.pay_cheque_seq = Convert.ToInt32(lblPayChequeSeq.Text);
                info.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                info.updated_when = DateTime.Now;
                paycheque.Delete(info);
            }

            List<M_FIM_PaymentCheques> listInfo = (List<M_FIM_PaymentCheques>)grdCheque.DataSource;
            listInfo.RemoveAt(Convert.ToInt32(lblIndex.Text));
            grdCheque.DataSource = listInfo;
            grdCheque.DataBind();

            PanelEditCheque.Visible = false;
            cmdAddNew.Visible = true;
            divControl1.Visible = true;
        }

        protected void ddlFilterBgmSourceSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
            LoadRadGrid2();
            RadGrid2.DataBind();
            // RadGrid2AfterBind();
            LoadDDLBankAccSeq();
            LoadDDLFromBankAccSeq();
            LoadDdlReceiveSeq();
        }

        protected void ddlFilterWorkAreaSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadRadGrid2();
            RadGrid2.DataBind();
            // RadGrid2AfterBind();
        }

        protected void txtBgmYear_TextChanged(object sender, EventArgs e)
        {
            lblBgmYear.Text = txtBgmYear.Text;
            LoadRadGrid2();
            RadGrid2.DataBind();
            // RadGrid2AfterBind();
        }

        //==========================================================================

        protected void rblMethodSeq_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rblMethodSeq.SelectedIndex.Equals("1") || rblMethodSeq.SelectedIndex.Equals("2"))
            {
                PanelTransfer.Visible = false;
                if (rblMethodSeq.SelectedValue.Equals("2")) PanelCheque.Visible = true;
                else PanelCheque.Visible = false;

            }
            else if (rblMethodSeq.SelectedIndex.Equals("3"))
            {
                PanelTransfer.Visible = true;
                PanelCheque.Visible = false;
                int? conid = main.ConvertNullInt(ViewState["_tmpConId"].ToString());
                LoadDDLToContactBankAccSeq(conid);
                ddlToConBankAcc.Visible = true;
                lblFromAcc.Visible = true;
                ddlFromBankAcc.Visible = true;
            }
            else if (rblMethodSeq.SelectedIndex.Equals("4"))
            {
                PanelTransfer.Visible = true;
                PanelCheque.Visible = false;
                int? conid = main.ConvertNullInt(ViewState["_tmpConId"].ToString());
                LoadDDLToContactBankAccSeq(conid);
                ddlToConBankAcc.Visible = true;
                lblFromAcc.Visible = false;
                ddlFromBankAcc.Visible = false;
            }
        }

        protected void ddlBankAccSeq_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDDLChequeSeq();
        }

        protected void cmdApprove_Click(object sender, EventArgs e)
        {
            PanelMessageSend.Visible = true;
            LoadApprover();
            Page.SetFocus(cmdSave);
        }

        protected void LoadApprover()
        {
            cmdApprove.Visible = false;
            //var pos_seq = send.GetPosSeqFromEmpSeq(Session["EmpSeq"].ToString());
            DataTable dtb = send.GetCurrentApprover(Session["EmpSeq"].ToString(), null, "FIM_PAYMENTS", 1);

            if (dtb != null)
            {
                if (dtb.Rows.Count > 0)
                {
                    lblApprovePathSeq.Text = dtb.Rows[0]["approve_path_seq"].ToString();
                    //ddlApprover.SelectedValue = dtb.Rows[0]["emp_seq"].ToString();
                    LoadEmpInfo(dtb.Rows[0]["emp_seq"].ToString());
                }
            }
            //}
            //else
            //{
            //    var model = send.GetInfoFromRefSeq(lblMoneyReqSeq.Text, "fim_money_requests");
            //    lblApprovePathSeq.Text = model.approve_path_seq.ToString();
            //    ddlApprover.SelectedValue = model.to_emp_seq.ToString();
            //    ddlApprover_SelectedIndexChanged(null, null);
            //}
        }

        protected void LoadEmpInfo(string strEmpSeq)
        {
            if (strEmpSeq.Length > 0)
            {
                var model = emplist.GetInfo(strEmpSeq);

                lblEmpSeq.Text = model.emp_seq.ToString();
                ddlApprover.Text = model.emp_name;
                lblAppPosName.Text = model.pos_name;
                lblAppClassName.Text = model.class_name;
                lblAppExecPosName.Text = model.exec_pos_name;
                lblAppJobsiteName.Text = model.job_site_name;
            }
        }

        protected void cmdRealPay_Click(object sender, EventArgs e)
        {
            PanelRealPay.Visible = true;
            txtReceiptNo.Text = "";
            txtReceiptName.Text = "";
            dpRealPayDate.SetValue(DateTime.Today);

            Page.SetFocus(cmdSave2);
        }

        protected void ddlApprover_DataBound(object sender, EventArgs e)
        {
            //set the initial footer label
            ((Literal)ddlApprover.Footer.FindControl("RadComboItemsCount")).Text = Convert.ToString(ddlApprover.Items.Count);
        }

        protected void ddlApprover_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            ddlApprover.DataSource = emplist.GetFull(null, null, null);
            ddlApprover.DataBind();
        }

        protected void ddlApprover_ItemDataBound(object sender, RadComboBoxItemEventArgs e)
        {
            e.Item.Text = ((M_HRM_PS_Employees)e.Item.DataItem).emp_name;
            e.Item.Value = ((M_HRM_PS_Employees)e.Item.DataItem).emp_seq.ToString();
        }

        protected void ddlApprover_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            SetEmpInfo(ddlApprover.SelectedValue);
        }

        protected void SetEmpInfo(string strEmpSeq)
        {
            if (strEmpSeq.Length > 0)
            {
                M_HRM_PS_Employees info = emplist.GetInfo(strEmpSeq);

                lblEmpSeq.Text = info.emp_seq.ToString();
                ddlApprover.Text = info.emp_name;
                lblAppPosName.Text = info.pos_name;
                lblAppClassName.Text = info.class_name;
                lblAppExecPosName.Text = info.exec_pos_name;
                lblAppJobsiteName.Text = info.working_job_site_name;
            }
        }

        protected void cmdSave_Click(object sender, EventArgs e)
        {
            if (lblEmpSeq.Text.Length == 0)
            {
                ((RadAjaxManager)Master.FindControl("RadAjaxManager1")).Alert("คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง");
                //RadAjaxManager1.Alert("คำเตือน!! กรุณาเลือกผู้อนุมัติก่อนส่ง");
                return;
            }

            try
            {
                string strPaySeq = lblPaySeq.Text;
                M_MessageSend info = new M_MessageSend();
                info.send_date = DateTime.Today;
                info.ref_seq = main.ConvertNullInt(strPaySeq);
                info.ref_type = "fim_payments";
                info.ref_no = lblPayRefNo.Text;
                info.send_text = "ส่งขออนุมัติ " + txtPayName.Text;
                info.from_emp_seq = main.ConvertNullInt(Session["EmpSeq"]);
                info.from_pos_seq = send.GetPosSeqFromEmpSeq("" + Session["EmpSeq"]);
                info.to_emp_seq = main.ConvertNullInt(lblEmpSeq.Text);
                info.to_pos_seq = send.GetPosSeqFromEmpSeq(lblEmpSeq.Text);
                info.approve_path_seq = main.ConvertNullInt(lblApprovePathSeq.Text);
                info.from_send_seq = null;
                info.remarks = null;
                info.message_status = "0";
                info.created_by = main.ConvertNullInt(Session["EmpSeq"]);
                info.created_when = DateTime.Now;
                send.Insert(info);

                M_FIM_Payments info2 = new M_FIM_Payments();
                info2.pay_seq = Convert.ToInt32(strPaySeq);
                info2.record_status = "P";
                info2.updated_by = main.ConvertNullInt(Session["EmpSeq"]);
                info2.updated_when = DateTime.Now;
                pay.ChangeStatus(info2);
                cmdApprove.Enabled = false;
                main.MessageAlert(Page, "บันทึกเรียบร้อยแล้ว");

                PanelMessageSend.Visible = false;
                PanelView.Visible = true;
                PanelEdit1.Visible = false;
                LoadRadGrid2();
                RadGrid2.DataBind();
                // RadGrid2AfterBind();
            }
            catch
            {
                main.MessageAlert(Page, "เกิดข้อผิดพลาดในการบันทึกข้อมูล");
            }
        }

        public void UpdatePayCheckMultiple(int[] paySeqs)
        {
            main.MessageAlert(Page, "บันทึกการจ่ายเงินสำเร็จจำนวน " + "");
            // cheque.DoPayCheckMulti(paySeqs));
        }

        protected void cmdUpdate3_Click(object sender, EventArgs e)
        {
            M_FIM_Cheques info = new M_FIM_Cheques();
            string strChequeBookSeq = lblChequeBookSeq.Text;
            string strChequeSeq = lblChequeSeq.Text;
            string strBankAccSeq = lblBankAccSeq.Text;
            string strChequeNo = lblChequeNo.Text;
            string strPaydate = dpChequePayDate.GetStringValue();
            string strChequedate = dpChequeDate.GetStringValue();
            string strReceiver = txtReceiver.Text;
            string strRemarks = txtChequeRemarks.Text;
            string strChequeStatus = rblChequeStatus.SelectedValue;
            string strUserID = Session["EmpSeq"].ToString();
            Nullable<DateTime> dtActualPayDate = txtActualPayDate.GetDateValue();
            DateTime dtNow = DateTime.Now;

            lblErrorActualPayDate.Visible = false;

            info.cheque_seq = Convert.ToInt32(strChequeSeq);
            info.cheque_book_seq = main.ConvertNullInt(strChequeBookSeq);
            info.bank_acc_seq = main.ConvertNullInt(strBankAccSeq);
            info.cheque_no = main.ConvertNullInt(strChequeNo);
            info.pay_date = main.ConvertNullDateTime(strPaydate);
            info.cheque_date = main.ConvertNullDateTime(strChequedate);
            info.actual_pay_date = dtActualPayDate;
            info.receiver = strReceiver;
            info.remarks = strRemarks;
            info.cheque_status = strChequeStatus;
            info.updated_by = main.ConvertNullInt(strUserID);
            info.updated_when = dtNow;

            cheque.Update(info);

            if (info.pay_date.HasValue)
            {
                var model = new M_FIM_Payments();
                model.pay_seq = Convert.ToInt32(lblPaySeq.Text);
                model.real_pay_date = info.pay_date;
                model.receipt_no = null;
                model.receipt_name = null;
                model.updated_by = main.ConvertNullInt(strUserID);
                model.updated_when = dtNow;
                pay.UpdateReceipt(model);
            }

            LoadRadGrid2();
            RadGrid2.DataBind();
            PanelPayCheque.Visible = false;
        }

        protected void cmdCancel3_Click(object sender, EventArgs e)
        {
            lblChequeBookSeq.Text = "";
            lblChequeSeq.Text = "";
            lblBankAccSeq.Text = "";
            lblChequeNo.Text = "";
            dpChequePayDate.SetValue(null);
            dpChequeDate.SetValue(null);
            txtReceiver.Text = "";
            txtChequeRemarks.Text = "";
            //rblChequeStatus.SelectedValue = "";
            txtActualPayDate.SetValue(null);

            PanelPayCheque.Visible = false;
        }

        protected void rblChequeStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            liActualPayDate.Visible = rblChequeStatus.SelectedValue == "3";
        }

        protected void cmdSave2_Click(object sender, EventArgs e)
        {
            string strReceiptNo = txtReceiptNo.Text;
            string strReceiptName = txtReceiptName.Text;
            DateTime? dtRealPayDate = dpRealPayDate.GetDateValue();

            if (dtRealPayDate == null)
            {
                lblErrorRealPayDate.Visible = true;
                return;
            }
            else
            {
                lblErrorRealPayDate.Visible = false;
            }
            
            var model = new M_FIM_Payments();
            model.pay_seq = Convert.ToInt32(lblPaySeq.Text);
            model.real_pay_date = dtRealPayDate;
            model.receipt_no = strReceiptNo;
            model.receipt_name = strReceiptName;
            model.updated_by = main.ConvertNullInt(Session["EmpSeq"].ToString());
            model.updated_when = main.ConvertNullDateTime(DateTime.Now);
            pay.UpdateReceipt(model);

            PanelMessageSend.Visible = false;
            PanelRealPay.Visible = false;
            PanelView.Visible = true;
            PanelEdit1.Visible = false;
            LoadRadGrid2();
            RadGrid2.DataBind();
            // RadGrid2AfterBind();
        }

        protected void RadGrid2_ItemDataBound(object sender, GridItemEventArgs e)
        {
            //if (e.Item is GridDataItem)
            //{
            //    GridDataItem item = (GridDataItem)e.Item;
            //    var strStatus = item["record_status_name"].Text;
            //    var strSeq = item["pay_seq"].Text;
            //    var strContactSeq = item["contact_seq"].Text;
            //    string strTax = item["tax"].Text;
            //    LinkButton lbtnadd = (LinkButton)item["TemplateColumn1"].FindControl("cmdPrintPopup");
            //    LinkButton lbtntax = (LinkButton)item["TemplateColumn2"].FindControl("cmdPrintPopupTax");
            //    lbtnadd.Visible = false;

            //    //ปิดการซ่อนตาม requirement 28/03/2557
            //    //lbtntax.Visible = (main.ConvertNullDouble(strTax) ?? 0) > 0; //แก้ตาม requirement 2557/03/24

            //    if (strStatus.StartsWith("จ่าย"))
            //    {
            //        lbtnadd.Visible = true;
            //    }
            //}
        }

        //private void SetVisibleCmdMultiActionSelectLink(string command = "StopMultiAction")
        //{
        //    cmdMultiSelectStart.Visible = command == "StopMultiAction" && RadGrid2.Visible;
        //    cmdMultiSelectStop.Visible = command == "StartMultiAction" && RadGrid2.Visible;
        //    cmdApproveConfirmPopup.Visible = command == "StartMultiAction" && RadGrid2.Visible;
        //    tbReasons.Visible = command == "StartMultiAction" && RadGrid2.Visible;
        //    RadGrid2.MasterTableView.GetColumn("action_select").Visible = command == "StartMultiAction";
        //    RadGrid2.AllowMultiRowSelection = command == "StartMultiAction";
        //    RadGrid2.ClientSettings.EnablePostBackOnRowClick = command != "StartMultiAction";
        //    RadGrid2.ClientSettings.Selecting.EnableDragToSelectRows = command == "StartMultiAction";
        //    RadGrid2.ClientSettings.Selecting.AllowRowSelect = true; //= command == "StartMultiAction";
        //    if (command == "StopMultiAction")
        //    {
        //        RadGrid2.PageSize = 10;
        //        RadGrid2.CssClass = "";
        //    }
        //    else
        //    {
        //        RadGrid2.PageSize = 100;
        //        RadGrid2.CssClass = "MyGridClass";
        //    }
        //}

        protected void LoadDdlReceiveSeq()
        {
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtReceiveBgmYear.Text;
            string strPaySeq = lblPaySeq.Text.Length > 0 ? lblPaySeq.Text : null;

            var models = r.GetNotPayments(strBgmSourceSeq, null, strBgmYear, strPaySeq);

            ddlReceiveSeq.DataSource = models;
            ddlReceiveSeq.DataBind();

            main.InsertEmptyDDLSelect(ddlReceiveSeq);
        }

        protected void cmdAdd_Click(object sender, EventArgs e)
        {
            if (ddlReceiveSeq.SelectedValue.Length > 0 && txtAmount.Value.HasValue)
            {
                string strReceiveSeq = ddlReceiveSeq.SelectedValue;
                var models = (List<M_FIM_Receives>)ViewState["data"];
                var model = r.GetInfo(strReceiveSeq);
                divReceive.Visible = true;

                foreach (var model1 in models)
                {
                    if (model.receive_seq == model1.receive_seq)
                    {
                        main.MessageAlert(Page, "รายการซ้ำ");
                        return;
                    }
                }
                model.amount = txtAmount.Value;
                model.vat_amount = main.ConvertNullDecimal(txtVatAmount.Value) ?? 0;

                models.Add(model);
                ViewState["data"] = models;
                RadGrid3.DataSource = models;
                RadGrid3.DataBind();

                ddlReceiveSeq.SelectedIndex = 0;
                CalculateSumAmount();
            }
            else
            {
                main.MessageAlert(Page, "กรองข้อมูลให้ถูกต้อง");
            }
        }

        protected void CalculateSumAmount()
        {
            double dAmount = 0;
            double dVatAmount = 0;
            foreach(GridDataItem item in RadGrid3.Items)
            {
                dAmount += main.ConvertNullDouble(main.WebString(item["amount"].Text)) ?? 0;
                dVatAmount += main.ConvertNullDouble(main.WebString(item["vat_amount"].Text)) ?? 0;
            }

            lblAmount.Text = dAmount.ToString("#,##0.00");
            lblVatAmount.Text = dVatAmount.ToString("#,##0.00");
        }

        protected void LoadRadGrid3()
        {
            int? nPaySeq = main.ConvertNullInt(lblPaySeq.Text);

            if (nPaySeq.HasValue)
            {
                ViewState["data"] = r.GetPayments(nPaySeq.Value);
                RadGrid3.DataSource = (List<M_FIM_Receives>)ViewState["data"];
                RadGrid3.DataBind();
            }

            CalculateSumAmount();
        }

        protected void RadGrid3_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Sort" || e.CommandName == "Filter")
            {
                var models = (List<M_FIM_Receives>)ViewState["data"];
                RadGrid3.DataSource = models;
                RadGrid3.DataBind();

                CalculateSumAmount();
            }
            else if (e.CommandName == "Delete")
            {
                var models = (List<M_FIM_Receives>)ViewState["data"];
                var item = (GridDataItem)e.Item;
                int receive_seq = main.ConvertNullInt(main.WebString(item["receive_seq"].Text)) ?? 0;
                var model = models.Where(m => m.receive_seq == receive_seq).FirstOrDefault();

                models.Remove(model);
                ViewState["data"] = models;
                RadGrid3.DataSource = models;
                RadGrid3.DataBind();

                CalculateSumAmount();
                LoadDdlReceiveSeq();
            }
        }

        protected void cmdAddNewRecord_Click(object sender, EventArgs e)
        {
            PanelEdit1.Visible = true;
            PanelView.Visible = false;
            cmdInsert1.Visible = true;
            cmdUpdate1.Visible = false;
            cmdDelete1.Visible = false;
            cmdApprove.Visible = false;
            cmdRealPay.Visible = false;
            PanelMessageSend.Visible = false;
            divControl1.Visible = true;
            rblMethodSeq.Enabled = true;

            lblRecordStatus.Text = "W";
            LoadData(null);
            LoadDdlReceiveSeq();
            var models = new List<M_FIM_Receives>();
            ViewState["data"] = models;
            RadGrid3.DataSource = models;
            RadGrid3.DataBind();

            CalculateSumAmount();
        }

        protected void txtReceiveBgmYear_TextChanged(object sender, EventArgs e)
        {
            LoadDdlReceiveSeq();
        }

        protected void ddlReceiveSeq_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(ddlReceiveSeq.SelectedValue))
            {
                var item = r.GetInfo(ddlReceiveSeq.SelectedValue);

                txtAmount.Text = (item.amount ?? 0).ToString();
                txtVatAmount.Text = (item.vat_amount ?? 0).ToString();
            }
        }
    }
}
